import {baseUrl,TokenUrl} from '../config/baseUrl'
let isRefreshing = true; // 请求锁
let pendings = []; // 请求列表
function request({
  url,
  data,
  method
}) {
  return new Promise((resolve, reject) => {
    let token = wx.getStorageSync('token')
    wx.request({
      url: baseUrl + url,
      data,
      method,
      header: {
        token
      },
      success(res) {
        let data = res.data
        if (data.code === 200) {
          resolve(data)
        }else if (data.code == '10000') {
                    if (isRefreshing) {
                        updateToken();
                        isRefreshing = false;
                        pendings.push(() => {
                            resolve(request({method, url, data}))
                        })
                    }
                }
        else {
              wx.showToast({
                title: data.msg,
                icon: 'error'
              })
              reject(data)
            }
          },
      fail(res) {
        wx.showToast({
          title: '请求出错',
          icon: 'none'
        })
      }
    })
  })
}

function post({
  url,
  data
}) {
  return request({
    url,
    data,
    method: 'POST'
  })
}
// 重新获取token
function updateToken(){
    wx.login({
      success (res) {
        wx.request({
            url: baseUrl + '/user/getopenid',
            method: 'POST',
            data: {
                code: res.code
            },
            success(rs) {
                if (rs.data.code == 200) {
					          wx.setStorageSync('token',rs.data.data.token);
                    wx.setStorageSync('session_key',rs.data.data.session_key);
                    wx.setStorageSync('openid',rs.data.data.openid);
                    wx.setStorageSync('nickName',rs.data.data.nickname);
			              wx.setStorageSync('avatarUrl',rs.data.data.headimgurl);
                    pendings.map((callback) => {
                        callback();
                    })
                    isRefreshing = true;
                } else {
                    toLogin();
                }
            }
        })
      }
    })
  }
// 前往登录页面 清空状态
function toLogin() {
    wx.showToast({
        title: '登录失效,请重新登录',
        icon: "none",
        success: () => {    
            pendings = [];
            isRefreshing = true;
        }
    })
}
export {
  post
}